package org.adorsys.aderp.cash.web;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.adorsys.aderp.cash.domain.CashReceipt;
import org.adorsys.aderp.cash.work.cashcollect.DateConfig;
import org.adorsys.aderp.cash.work.cashcollect.DateConfigPeriod;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/cashreceipts")
@Controller
@RooWebScaffold(path = "cashreceipts", formBackingObject = CashReceipt.class)
public class CashReceiptController {
	@RequestMapping(value="/myCashForToDay",method=RequestMethod.GET)
	public String myCashCollectedToday(Model uiModel){
		String userName = SecurityUtils.getUserName();
		DateConfigPeriod begingEndOfDay = DateConfig.getBegingEndOfDay(new Date());
    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
    	String begin = simpleDateFormat.format(begingEndOfDay.getBegin());
    	String end = simpleDateFormat.format(begingEndOfDay.getEnd());
    	List<CashReceipt> cashReceipts = cashReceiptService.findByCashierAndCashDateBetween(userName, begingEndOfDay.getBegin(), begingEndOfDay.getEnd());
    	uiModel.addAttribute("begin", begin);
    	uiModel.addAttribute("end", end);
    	return computeDetailAndShowResults(cashReceipts, uiModel);
	}
	
	private String computeDetailAndShowResults(List<CashReceipt> cashReceipts,Model uiModel){
		BigDecimal totalCashAmount = BigDecimal.ZERO;
		for (CashReceipt cashReceipt : cashReceipts) {
			totalCashAmount = totalCashAmount.add(cashReceipt.getAmountDue());
		}
		System.out.println("Cash collected"+totalCashAmount);
		uiModel.addAttribute("totalCashAmout", totalCashAmount);
		return "cashreceipts/cashList";
	}
}	
